import time

visit_history = {

}


class MyThrottle(object):

	def allow_request(self, request, view):
		# 限制10秒访问3次
		# 获取ip
		ip = request.META.get('REMOTE_ADDR')

		if not visit_history.get(ip):
			visit_history[ip] = []
		history = visit_history[ip]  # [ 12:04:15  ,12:04:10 , 12:04:05 ]
		self.history = history
		now = time.time()

		while history and now - history[-1] > 10:
			history.pop()

		if len(history) >= 3:
			return False
		else:
			history.insert(0, now)
			return True

	def wait(self):

		return self.history[-1] + 10 - time.time()


from rest_framework.throttling import SimpleRateThrottle


class MySimpleRateThrottle(SimpleRateThrottle):
	scope = 'xxxx'

	def get_cache_key(self, request, view):
		return self.get_ident(request)
